import Vue from 'vue'
import http from 'vue-resource'
import * as constants from 'src/AppConstants'
import store from 'store'
import utils from 'commons/utils'
import env from 'commons/env'
import EventBus from 'eventbusjs'

Vue.use(http)
Vue.http.options.root = env.API
Vue.http.options.emulateJSON = true

const HEADER_API_TOKEN = constants.API_TOKEN	// API_TOKEN请求头
const HEADER_CHANNEL = constants.CHANNEL	   // 渠道请求头

/**
 * 显示加载提示框
 * @param request   HTTP请求对象
 * @param store     vux对象
 * @param status    true：显示，false：隐藏
 */
const onShowLoading = function (loadingParams, status) {
  let _store = store
  let __showLoading = loadingParams.__showLoading
  if (__showLoading !== undefined) {
    if (__showLoading === true) {
      _store.dispatch('showLoading', status)
    }
  } else {
    _store.dispatch('showLoading', status)
  }
}

/**
 * 显示提示框
 * @param request   HTTP请求对象
 * @param store     vux对象
 * @param text      提示文字
 */
const onShowTip = function (loadingParams, text) {
  let _store = store
  let __showTip = loadingParams.__showTip
  if (__showTip !== undefined) {
    if (__showTip === true) {
      _store.dispatch('showTip', text)
    }
  } else {
    _store.dispatch('showTip', text)
  }
}

// 全局拦截请求和响应
Vue.http.interceptors.push((request, next) => {
  let _store = store

  let loadingParams = {}
  if (request.body || request.params) {
    Object.assign(loadingParams, request.body || request.params)
    if (request.body) {
      delete request.body.__showLoading
      delete request.body.__showTip
    } else if (request.params) {
      delete request.params.__showLoading
      delete request.params.__showTip
    }

  }
  onShowLoading(loadingParams, true)

  let sign
  if (request.body) {
    sign = utils.getSign(request.body)
    if (sign) {
      request.body[constants.PARAM_SIGN_NAME] = sign   // 添加签名参数
    }
  } else if (request.params) {
    sign = utils.getSign(request.params)
    if (sign) {
      request.params[constants.PARAM_SIGN_NAME] = sign   // 添加签名参数
    }
  }

  // 公共请求头
  let apiToken = localStorage.getItem(HEADER_API_TOKEN)
  request.headers.set(HEADER_API_TOKEN, apiToken || '')
  request.headers.set(HEADER_CHANNEL, utils.getChannel())

  // 全局处理http响应
  next((response) => {
    onShowLoading(loadingParams, false)
    if (response.body && response.body.code === constants.RESPONSE_CODE_SUCCESS) {
      console.debug("request success:", JSON.stringify(response.body))
      return
    }

    if (response.body) {
      console.warn("request error:", response.body)
      response.ok = false
      response.status = response.body.code
      response.statusText = response.body.tip
      response.body = {
        code: response.body.code,
        tip: response.body.tip
      }
      // API_Token失效
      if (response.body.code === constants.RESPONSE_CODE_API_TOKEN_INVALID) {
        _store.dispatch('logout', true).then(() => {
          EventBus.dispatch(constants.EVENT_LOGOUT_SUCCESS)
        })
      }
    } else {
      console.error("request error:", response)
      response.ok = false
      response.status = '-1'
      response.statusText = '服务器异常'
      response.body = {
        code: constants.RESPONSE_CODE_SER_ERROR,
        tip: '服务器异常'
      }
    }
    onShowTip(loadingParams, response.body.tip)
  })
})


// WEBPACK FOOTER //
// ./src/plugins/http.js
